//列表方式显示文档支持： 删除  只读  网络可用情况下：共享(开启 关闭 白名单)，服务器可缓存 收益值 收益记录 )

import 'package:eshi/app/CommonFunctions.dart';
import 'package:eshi/app/shi/data/Config.dart';
import 'package:eshi/app/shi/data/HistoryConfig.dart';
import 'package:eshi/app/shi/data/tabtxt_history.dart';
import 'package:eshi/app/shi/taxis/TabEditPage.dart';
import 'package:eshi/app/shi/widget/CommonWidgets.dart';
import 'package:flutter/material.dart';

class DataManage extends StatefulWidget{
  var buttonStyle = TextButton.styleFrom(
                       backgroundColor: Colors.grey[100],
                       minimumSize: const Size(0, 0),
                       padding: const EdgeInsets.symmetric(horizontal: 5),
                    );
  DataManage({super.key});
  @override
  State<StatefulWidget> createState() => DataManageState();

}

class DataManageState extends State<DataManage>{
  get data => HistoryConfig.getAll();

  bool boolConf(dname,name,{bool? value}){
      if(value!=null){
          switch(name){
            case "只读":
              var newValue = Config.historyReadOnlyList;
              value ? newValue.add(dname) : newValue.remove(dname);
              Config.historyReadOnlyList = newValue;
              break;
            case "停用":
              var newValue = Config.historyDisableList;
              value ?  newValue.add(dname): newValue.remove(dname);
              Config.historyDisableList = newValue;
          }  
          setState(() {
            
          });
          return true;
      }
      switch(name){
        case "只读":
          return Config.historyReadOnlyList.contains(dname);
        case "停用":
          return Config.historyDisableList.contains(dname);
      }
      return true;
  }
  Widget BoolAttr(dname,String name){
      var value = boolConf(dname,name);
      return TextButton(
        style:  widget.buttonStyle,
        child: mText(name,style: TextStyle(color: value?Colors.green:Colors.grey),),
        onPressed: (){
            value = boolConf(dname,name,value:!value);
        },);
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading:false,
        actions: [
           Row(mainAxisAlignment: MainAxisAlignment.end, children: [
              FloatingActionButton(shape: CircleBorder(),child: Icon(Icons.add),onPressed: (){
                   modeWindow(context, TabEditPage(title:"",data:data,onChange:(newData,marks,title){
                              Navigator.pop(context);
                              TabTxtHistory.update(title, newData);
                    }));
              }),
              SizedBox(width: 20,),
            ]),
          //  Container(
          //     decoration: BoxDecoration(
          //       border: Border.all(
          //         color: Colors.blue, // 边框颜色
          //         width: 2, // 边框宽度
          //       ),
          //       borderRadius: BorderRadius.circular(28), // 边框圆角
          //     ),
          //     child:
          //      IconButton(
          //       icon: const Icon(Icons.add),
          //       onPressed: () {
          //           modeWindow(context, TabEditPage(title:"",data:data,onChange:(newData,marks,title){
          //                     TabTxtHistory.update(title, newData);
          //           }));
          //       },
          //       splashRadius:2,
          //       tooltip: "添加新项",
          //   )),
        ],
      ),
      body: ListView.separated(
        padding: const EdgeInsets.all(16),
        itemCount: data.length,
        separatorBuilder: (context, index) => const Divider(height: 1),
        itemBuilder: (context, index) {
            final itemIndex = index + 1; // 行号从1开始
            final name = data[index];
            final isReadOnly = HistoryConfig.isReadOnly(name);
            // 第一列：行号
            return  InkWell(
            // 单击事件
            onTap: () {},
            // 点击水波纹颜色
            splashColor: Colors.blue.withOpacity(0.2),
            // 高亮颜色（点击时的背景色）
            highlightColor: Colors.grey[200],
            child: Row(
              children: [
              SizedBox(
                width: 20,
                child: Text('$itemIndex'),
              ),
                // 第二列：内容
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 5),
                  child: Text(name),
                ),
              ),
              
              // 第三列：操作按钮
              Row(
                children: [
                  BoolAttr(name,"只读"),
                  BoolAttr(name,"停用"),
                  // BoolAttr("服务器可缓存"),

                  TextButton(
                    style:  widget.buttonStyle,
                    onPressed: (){
                      if(isReadOnly) return;
                      TabTxtHistory.loadContent(name).then((data){
                        modeWindow(context, TabEditPage(title:name,data:data,onChange:(newData,marks,title){
                              TabTxtHistory.update(name, newData);
                               Navigator.pop(context);
                        }));
                      });
                    },
                    child: isReadOnly ? mText('编辑',style:TextStyle(color: Colors.grey)) : mText('编辑'),
                  ),
                  TextButton(
                    style:  widget.buttonStyle,
                    onPressed: () async{
                      if(await confirm(msg:mt("删除之后无法恢复!"))){
                        await TabTxtHistory.remove(name);
                        setState(() {
                          
                        });
                      }
                    },
                    child: mText('删除', style: TextStyle(color: Colors.red)),
                  ),
                ],
              ),
            ],
          ));
        }
      )
    );
  }
}